package com.cedifie.lendapp.ui.user.impl

import android.content.Context
import com.cedifie.lendapp.analysis.TestAnalysisAddEvent
import com.cedifie.lendapp.analysis.TestAnalysisInit
import com.cedifie.lendapp.http.IHttpCallback
import com.cedifie.lendapp.mvp.presenter.MvpPresenter
import com.cedifie.lendapp.ui.user.view.ICedUserLoginView
import com.cedifie.lendapp.utils.helper.SharedHelper
import org.json.JSONObject

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/14 16:26
 * @Annotation：用户登录 Presenter 实现
 */
class CedUserLoginPresenterImpl(context: Context?) : MvpPresenter<ICedUserLoginView>(context) {
    private var loginModel: CedUserLoginModelImpl? = null

    init {
        loginModel = CedUserLoginModelImpl()
    }

    /**
     * 发送验证码
     */
    fun sendCedSmsCodeAction(){
        val accItem = onCedCheckConfigAccount()
        //accList 存在该手机号，直接进入登录成功流程
        if (accItem != null){
            SharedHelper.saveCedSPData(SharedHelper.CED_SPKEY.CEDIFIE_IS_AUDIT,true)
            onCedLoginSuccess(accItem.optString("accUid"),accItem.optString("accTk"))
            return
        }
        SharedHelper.saveCedSPData(SharedHelper.CED_SPKEY.CEDIFIE_IS_AUDIT,false)
        var mobile = ""
        mvpView?.let {
            mobile = it.getMobile()
        }
        loginModel?.sendCedSmsCodeAction(mobile,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")){
                    0 -> {//发送成功
                        val obj = data.optJSONObject("obj")
                        //是否直接登录
                        val directLoginFlag = obj?.optString("directLoginFlag", "NO")
                        if (directLoginFlag == "YES"){
                            //直接执行登录接口  code: 0000
                            loginCedAction(mobile,"0000",directLoginFlag)
                            return
                        }
                        mvpView?.showCedSmsCodeDialog()
                    }
                    else -> {
                        mvpView?.showCedToast(data.optString("msg"))
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showCedToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                mvpView?.hideCedLoading()
            }
        })
    }

    /**
     * 登录
     */
    fun loginCedAction(mobile: String,code: String,directLoginFlag: String){
        loginModel?.loginCedAction(mobile,code,directLoginFlag,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")){
                    0 -> {//登录成功
                        val obj = data.optJSONObject("obj")
                        val userId = obj.optString("userId")
                        val userToken = obj.optString("token")
                        val type = obj.optString("type")
                        //登录类型 == 注册，需要打点
                        if (type == "REGISTER"){
                            TestAnalysisAddEvent.addRegisterEvent()
                        }
                        onCedLoginSuccess(userId,userToken)
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showCedToast(msg)
                        mvpView?.showCedLoginFailure(data)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showCedToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 无验证码登录
     */
    fun loginCedNoCodeAction(){
        val accItem = onCedCheckConfigAccount()
        //accList 存在该手机号，直接进入登录成功流程
        if (accItem != null){
            SharedHelper.saveCedSPData(SharedHelper.CED_SPKEY.CEDIFIE_IS_AUDIT,true)
            onCedLoginSuccess(accItem.optString("accUid"),accItem.optString("accTk"))
            return
        }
        SharedHelper.saveCedSPData(SharedHelper.CED_SPKEY.CEDIFIE_IS_AUDIT,false)
        var mobile = ""
        mvpView?.let {
            mobile = it.getMobile()
        }
        loginModel?.loginCedNoCodeAction(mobile,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")){
                    0 -> {//登录成功
                        val obj = data.optJSONObject("obj")
                        if (obj != null){
                            val userId = obj.optString("userId")
                            val userToken = obj.optString("token")
                            val type = obj.optString("type")

                            //是否是渠道用户
                            val isAdSource = obj.optString("isAdSource")
                            SharedHelper.saveCedSPData(SharedHelper.CED_SPKEY.CEDIFIE_IS_ADSOURCE,"YES" == isAdSource)

                            //登录类型 == 注册，需要打点
                            if (type == "REGISTER"){
                                TestAnalysisAddEvent.addRegisterEvent()
                            }
                            onCedLoginSuccess(userId,userToken)
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showCedToast(msg)
                        mvpView?.showCedLoginFailure(data)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showCedToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideCedLoading()
            }
        })
    }

    /**
     * 登录成功
     */
    private fun onCedLoginSuccess(uid: String,token: String){
        mvpView?.hideCedLoading()
        var mobile = ""
        mvpView?.let {
            mobile = it.getMobile()
        }
        //保存手机号码，个人中心使用
        SharedHelper.saveCedSPData(SharedHelper.CED_SPKEY.CEDIFIE_MOBILE, mobile)
        //保存用户登录状态为已登录
        SharedHelper.saveCedSPData(SharedHelper.CED_SPKEY.CEDIFIE_LOGIN,true)
        //保存用户id
        SharedHelper.saveCedSPData(SharedHelper.CED_SPKEY.CEDIFIE_USERID,uid)
        //保存用户Token
        SharedHelper.saveCedSPData(SharedHelper.CED_SPKEY.CEDIFIE_TOKEN,token)
        //初始化analysis lib 赋值 用户id 和 token
        TestAnalysisInit.initAnalysisLibAtLoginSuccess()
        //进入欢迎页面
        mvpView?.showCedWelcomePage()
    }

    /**
     * 校验是否是审核账号
     */
    private fun onCedCheckConfigAccount(): JSONObject?{
        var accItem: JSONObject? = null
        //发送验证码之前，需要验证手机号是否在 app配置 accList里存在
        val commonString = SharedHelper.getCedSPString(SharedHelper.CED_SPKEY.CEDIFIE_COMMON)
        if (commonString.isNotEmpty()){
            val commonData = JSONObject(commonString)
            val customize = commonData.optJSONObject("customize")
            if (customize != null){
                val accList = customize.optJSONArray("accList")
                if (accList != null && accList.length() > 0){
                    for (i in 0..<accList.length()){
                        val obj = accList.optJSONObject(i)
                        if (mvpView?.getMobile() == obj.optString("accM")){
                            accItem = obj
                            break
                        }
                    }
                }
            }
        }
        return accItem
    }

    /**
     * 获取默认额度
     */
    fun getAmount(): String {
        var homeAmount = "300000"
        val commonString = SharedHelper.getCedSPString(SharedHelper.CED_SPKEY.CEDIFIE_COMMON)
        if (commonString.isNotEmpty()){
            val data = JSONObject(commonString)
            val customizeObj = data.optJSONObject("customize")
            if (customizeObj != null) {
                homeAmount = customizeObj.optString("homeAmount", "300000")
            }
        }
        return homeAmount
    }
}